package com.echovin.esb.gateway.locator;

import com.echovin.esb.gateway.model.GatewayServerAction;
import com.echovin.esb.gateway.service.GatewayServiceActionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class GatewayServiceActionResourceLocator {
    private Map<String, GatewayServerAction> resourceMap = new ConcurrentHashMap<>();
    @Autowired
    GatewayServiceActionService gatewayServiceActionService;

    public GatewayServiceActionResourceLocator() {
    }
    /**
     * 清空缓存并刷新
     */
    public void refresh() {
        this.resourceMap.clear();
        this.resourceMap.putAll(this.loadResourceDefine());
    }

    /**
     * 服务id->动作id
     * @param serviceId
     * @return
     */
    public String getServiceActionId(String serviceId) {
        if (StringUtils.isEmpty(serviceId)) {
            return null;
        }
        GatewayServerAction gatewayServerAction = this.resourceMap.get(serviceId);
        if (gatewayServerAction == null) {
            return null;
        }
        return gatewayServerAction.getId();
    }

    /**
     * 调用service查询所有的gateway服务动作，组装{[serviceId：gatewayServerAction]}
     */
    private Map<String, GatewayServerAction> loadResourceDefine() {
        Map<String, GatewayServerAction> map = new ConcurrentHashMap<>();
        try {
            List<GatewayServerAction> resourceList = gatewayServiceActionService.getGatewayServiceAction();
            if (resourceList == null) {
                return map;
            }

            Iterator var3 = resourceList.iterator();
            while(var3.hasNext()) {
                GatewayServerAction resource = (GatewayServerAction)var3.next();
                map.put(resource.getServiceId(), resource);
            }

        } catch (Exception e) {
            log.error("加载gateway服务错误:{}", e);
        }

        log.info("数据库加载服务动作{}", map.values());

        return map;
    }


}
